package com.eqdd.yiqidian.ui.companyspace

import android.content.Intent
import android.net.Uri
import android.view.View
import android.widget.PopupWindow
import com.eqdd.yiqidian.R
import com.eqdd.yiqidian.adapter.BGABannerAdapter
import com.eqdd.yiqidian.base.BaseActivity
import com.eqdd.yiqidian.base.Config
import com.eqdd.yiqidian.bean.CompanyDetailBean
import com.eqdd.yiqidian.bean.LeaveMessageBean
import com.eqdd.yiqidian.bean.ProductBean
import com.eqdd.yiqidian.http.DialogCallBack
import com.eqdd.yiqidian.http.HttpConfig
import com.eqdd.yiqidian.http.HttpResult
import com.eqdd.yiqidian.http.JsonCallBack
import com.eqdd.yiqidian.kotlin.bottomDialog
import com.eqdd.yiqidian.kotlin.deleteDialog
import com.eqdd.yiqidian.kotlin.imgPathPreview
import com.eqdd.yiqidian.share.JShareDialog
import com.eqdd.yiqidian.share.LinkShareBuilder
import com.eqdd.yiqidian.ui.InputDialogActivity
import com.eqdd.yiqidian.ui.mine.space.OwnerComSpaceActivity
import com.eqdd.yiqidian.utils.PreferenceUtil
import com.eqdd.yiqidian.widget.PromptPopWindow
import com.lzy.okgo.OkGo
import com.lzy.okgo.model.Response
import kotlinx.android.synthetic.main.activity_product_info.*
import kotlinx.android.synthetic.main.list_item_179.view.*
import org.jetbrains.anko.sdk25.coroutines.onClick
import org.jetbrains.anko.startActivity
import org.jetbrains.anko.startActivityForResult
import org.jetbrains.anko.toast
import java.util.*

/**
 * type-0: 其他进入
 * type-1: 人事进入
 * Created by jhj on 18-7-6.
 */
class ProductInfoActivity : BaseActivity() {

    private var id: Int = -1
    private var productBean: ProductBean? = null
    private var companyDetailBean: CompanyDetailBean? = null


    companion object {
        const val VISITOR_PRODUCT_INFO = "VISITOR_PRODUCT_INFO"
    }

    override fun initBinding() {
        var isCollection = false
        setContentView(R.layout.activity_product_info)
        initTopTitleBar(View.VISIBLE, "产品详情")
        val density = resources.displayMetrics.density
        id = intent.getIntExtra(Config.ID, -1)

        linearLayout.visibility = View.VISIBLE

        tv_more.onClick {
            val popWindow = PromptPopWindow.Builder(this@ProductInfoActivity)
                    .setLayoutRes(R.layout.list_item_179, object : PromptPopWindow.OnCustomListener {
                        override fun onLayout(view: View, popupWindow: PopupWindow?) {
                            view.tv_share.onClick {
                                if (productBean != null) {
                                    val uri = "https://www.eqidd.com/qiyeSpace/html/product.html?id=$id"
                                    val builder = LinkShareBuilder(this@ProductInfoActivity)
                                    builder.setTitle(productBean?.productName)
                                            .setId(productBean?.getId()?.toString())
                                            .setText(productBean?.productMsg)
                                            .setUrl(uri)
                                            .setImageUrl(productBean?.images?.get(0))
                                            .setSource("产品信息")
                                    JShareDialog(builder, this@ProductInfoActivity).show()
                                } else {
                                    toast("获取产品详情失败")
                                }
                            }
                            view.tv_message.onClick {
                                popupWindow?.dismiss()
                                startActivityForResult<InputDialogActivity>(Config.INPUT, Config.TALK_TO to "")
                            }
                            view.tv_collection.onClick {
                                popupWindow?.dismiss()
                                if (user.isAdmin > 0) {
                                    OkGo.post<HttpResult<*>>(HttpConfig.BASE_URL + HttpConfig.COLLECT_ADD)
                                            .params("userGuid", user.guid)
                                            .params("userCompanyId", user.companyId)
                                            .params("objectId", id)
                                            .params("objectType", 1)
                                            .params("objectCompanyId", companyDetailBean?.companyId
                                                    ?: 0)
                                            .execute(object : DialogCallBack<HttpResult<*>>(this@ProductInfoActivity) {
                                                override fun onSuccess(response: Response<HttpResult<*>>?) {
                                                    val result = response?.body()
                                                    if (result?.status == 200) {
                                                        if (!isCollection) toast("收藏成功")
                                                        isCollection = true
                                                    } else {
                                                        if (!isCollection) toast(result?.msg
                                                                ?: "收藏失败")
                                                        isCollection = true
                                                    }
                                                }
                                            })
                                }

                                OkGo.post<HttpResult<*>>(HttpConfig.BASE_URL + HttpConfig.MAKER_COLLECT_ADD)
                                        .params("userCompanyId", user.companyId)
                                        .params("userGuid", user.guid)
                                        .params("objectId", id) //被收藏的id（（企业/创客）产品id）
                                        .params("objectType", 1) //0:收藏企业，1：企业产品 ，2：创客产品，3：其他创客
                                        .params("objectGuid", "") //如果收藏的是创客，创客guid
                                        .params("objectCompanyId", companyDetailBean?.companyId
                                                ?: 0) //被收藏企业id
                                        .execute(object : DialogCallBack<HttpResult<*>>(this@ProductInfoActivity) {
                                            override fun onSuccess(response: Response<HttpResult<*>>?) {
                                                val result = response?.body()
                                                if (result?.status == 200) {
                                                    if (!isCollection) toast("收藏成功")
                                                    isCollection = true
                                                } else {
                                                    if (!isCollection) toast(result?.msg
                                                            ?: "收藏失败")
                                                    isCollection = true
                                                }
                                            }
                                        })

                            }
                            view.tv_company.onClick {
                                popupWindow?.dismiss()
                                if (companyDetailBean == null) {
                                    toast("请稍后")
                                    return@onClick
                                }
                                startActivity<OwnerComSpaceActivity>(Config.COMPANY_ID to companyDetailBean?.companyId)
                            }
                        }
                    })
                    .setBackgroundAlpha(0.9f)
                    .build()

            popWindow.showAsDropDown(tv_more, 35 * density.toInt(), -(popWindow.getHeight() + tv_more.height) - 2 * density.toInt())
        }

        tv_phone.onClick {
            if (companyDetailBean == null) {
                toast("请稍后")
                return@onClick
            }
            val phone = companyDetailBean?.comCotact?.contactNumber
            val intent = Intent(Intent.ACTION_DIAL)
            val url = Uri.parse("tel:$phone")
            intent.data = url
            startActivity(intent)
        }

        tv_purchase.onClick {

        }


        if (productBean?.companyId == user.companyId) {
            initTopRightImage(R.mipmap.addg) {
                val type = intent.getIntExtra(Config.TYPE, 0)
                val array = if (type == 1) arrayOf("查看产品供方信息", "查看产品买方信息", "删除") else arrayOf("查看产品供方信息", "查看产品卖方信息")
                bottomDialog(array.asList()) {
                    when (it) {
                        1 -> {
                            if (type == 1) {
                                startActivity<ProductSupplierListActivity>(Config.ID to productBean?.id, Config.TYPE to 0, "fun" to 0)
                            } else {
                                startActivity<ProductSupplierListActivity>(Config.ID to productBean?.id, Config.TYPE to 0, "fun" to 1)
                            }
                        }
                        2 -> {
                            if (type == 1) {
                                startActivity<ProductSupplierListActivity>(Config.ID to productBean?.id, Config.TYPE to 1, "fun" to 0)
                            } else {
                                startActivity<ProductSupplierListActivity>(Config.ID to productBean?.id, Config.TYPE to 1, "fun" to 1)
                            }
                        }
                        3 -> {
                            if (productBean != null) {
                                deleteDialog(HttpConfig.BASE_URL + HttpConfig.PRODUCT_DELETE, "是否删除${productBean?.productName ?: "该数据"}", "productId" to productBean?.id)
                            } else {
                                toast("删除失败")
                            }
                        }
                    }
                }
            }
        }


    }


    override fun initData() {

        if (id == -1) {
            toast("获取详情失败")
            finish()
            return
        }



        OkGo.post<HttpResult<ProductBean>>(HttpConfig.BASE_URL + HttpConfig.PRODUCT_INFO)
                .params("userGuid", user.guid)
                .params("companyId", user.companyId)
                .params("productId", id)
                .execute(object : DialogCallBack<HttpResult<ProductBean>>(this) {
                    override fun onSuccess(response: Response<HttpResult<ProductBean>>?) {
                        val result = response?.body()
                        if (result?.status == 200) {
                            productBean = result.items
                            val isVisitorSpace = intent.getBooleanExtra("isVisitorSpace", true)
                            if (isVisitorSpace) {
                                visitor("产品信息", "访问了${productBean?.productName
                                        ?: "产品信息"}", VISITOR_PRODUCT_INFO + (productBean?.companyId?.toString()
                                        + "_" + productBean?.id))
                            }
                            setView()
                            companyInfo()
                        } else {
                            toast("获取详情失败")
                            finish()
                        }
                    }

                })
    }

    private fun companyInfo() {
        if (productBean == null) {
            finish()
            return
        }
        OkGo.post<HttpResult<CompanyDetailBean>>(HttpConfig.BASE_URL + HttpConfig.COMPANY_SPACE_DETAIL)
                .params("userGuid", user.guid)
                .params("userGompanyId", user.companyId)
                .params("companyId", productBean?.companyId ?: 0)
                .execute(object : JsonCallBack<HttpResult<CompanyDetailBean>>() {
                    override fun onSuccess(response: Response<HttpResult<CompanyDetailBean>>?) {
                        val result = response?.body()
                        if (result?.status == 200) {
                            companyDetailBean = result.items


                        } else {
                            toast(result?.msg ?: "获取信息失败")
                            finish()
                            return
                        }
                    }

                })
    }

    override fun setView() {
        productBean?.let {
            richEditor.setInputEnabled(false)
            richEditor.setPadding(10, 0, 10, 0)
            val html = it.productInfo
                    ?.replace("<pre>", "")
                    ?.replace("</pre>", "")
                    ?.replace("<br>", "")
            richEditor.html = html
            tv_name.text = String.format(Locale.CHINA, "%s（%s）", it.productName, it.productType)
            tv_count.text = it.browseCount.toString()
            tv_circle.text = String.format(Locale.CHINA, "%d-%d天", it.deliveryCycle, it.deliveryCycle2)
            tv_price.text = String.format(Locale.CHINA, "￥%d元", it.productPrice)
            tv_area.text = it.area
            tv_standard.text = it.guoBiaoCode
            tv_model.text = it.productModel

            banner_viewpager.setAdapter(BGABannerAdapter(this))
            banner_viewpager.setData(it.images, null)
            banner_viewpager.setDelegate { banner, itemView, model, position ->
                imgPathPreview(it.images, position)
            }
        }
    }

    private fun visitor(mudular: String, option: String, key: String) {
        val companyId = productBean?.companyId ?: 0

        val time = PreferenceUtil.find(this, key, String::class.java)
        if (time == null || time.toLong() < System.currentTimeMillis() - 30 * 60 * 1000) {
            OkGo.post<HttpResult<*>>(HttpConfig.BASE_URL + HttpConfig.SPACE_VISITOR_ADD)
                    .params("userGuid", user.guid)
                    .params("userCompanyId", user.companyId)
                    .params("companyId", companyId)
                    .params("mudular", mudular)
                    .params("option", option)
                    .execute(object : JsonCallBack<HttpResult<*>>() {
                        override fun onSuccess(response: Response<HttpResult<*>>?) {
                            val result = response?.body()
                            if (result?.status == 200) {
                                PreferenceUtil.save(this@ProductInfoActivity, System.currentTimeMillis().toString(), key)
                                print(mudular)
                            }
                        }
                    })
        }
    }

    fun responseMessage(msg: String) {
        OkGo.post<HttpResult<LeaveMessageBean>>(HttpConfig.BASE_URL + HttpConfig.LEAVE_MESSAGE_ADD)
                .params("userGuid", user.guid)
                .params("userCompanyId", user.companyId)
                .params("message", msg)
                .params("companyId", productBean?.companyId ?: 0)
                .params("parentId", 0)
                .params("parentUserGuid", 0)
                .params("firstCommentId", 0)
                .params("objectId", id)
                .params("objectType", "产品信息")
                .execute(object : DialogCallBack<HttpResult<LeaveMessageBean>>(this) {
                    override fun onSuccess(response: Response<HttpResult<LeaveMessageBean>>?) {
                        val result = response?.body()
                        if (result?.status == 200) {
                            toast(result.msg)
                        } else {
                            toast(result?.msg ?: "")
                        }
                    }

                })
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode == Config.SUCCESS) {
            when (requestCode) {
                Config.INPUT -> {
                    val str = data?.getStringExtra(Config.CONTENT)
                    responseMessage(str ?: "")
                }
            }
        }
    }
}